// cmdutils.cpp
#include <stdio.h>
#include <string.h>
#include "cmdutils.h"

int parse_options(Option *options, int argc, char *argv[]) 
{
    for (int i = 1; i < argc; i++) {
        int matched = 0;

        for (Option *opt = options; opt->name != NULL; opt++) {
            if (strcmp(argv[i], opt->name) == 0) {
                if (opt->has_arg && i + 1 < argc) {
                    opt->handler(argv[++i]);  // 调用带参数的 handler
                } else if (!opt->has_arg) {
                    opt->handler(NULL);       // 调用无参数的 handler
                } else {
                    fprintf(stderr, "Option %s requires an argument.\n", argv[i]);
                    return -1;
                }
                matched = 1;
                break;
            }
        }

        if (!matched) {
            fprintf(stderr, "Unknown option: %s\n", argv[i]);
            return -1;
        }
    }

    return 0;
}